#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import time
import jwt  

#  pip3 install pyjwt

JWT_TOKEN_EXPIRE_TIME = 3600 * 24  # token有效时间 24小时
JWT_SECRET = 'woshiwuwei'   # 加解密密钥
JWT_ALGORITHM = 'HS256'  # 加解密算法


def generate_jwt_token(userid: int,username:str,realname:str,userstatus:int,menucode:str)->str:
    """
        @summary: 根据参数生成token
        @param userid:用户id,必填,int类型,并将条件值传递进来
        @param username:用户名,必填,str类型,并将条件值传递进来
        @param realname:姓名,必填,str类型,并将条件值传递进来
        @param userstatus:用户状态码,必填,str类型,并将条件值传递进来
        @param menucode:用户访问的菜单编号,必填,str类型,并将条件值传递进来
        @return: 返回token str类型
    """
    payload = {'userid': userid,'username': username,'realname': realname,'userstatus': userstatus,'menucode': menucode, 'exp': int(time.time()) + JWT_TOKEN_EXPIRE_TIME}
    token = jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
    return token

def verify_jwt_token(token: str)->bool:
    """验证用户token"""
 
    try:
        _payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
    except jwt.PyJWTError:
        print('token解析失败')
        return False
    else:
        print(_payload)
        exp = int(_payload.pop('exp'))
        if time.time() > exp:
            print('已失效')
            return False
        return _payload 
    
# def verify_jwt_token(userid: int, token: str)->bool:
#     """验证用户token"""
#     payload = {'userid': userid}
#     try:
#         _payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
#     except jwt.PyJWTError:
#         print('token解析失败')
#         return False
#     else:
#         print(_payload)
#         exp = int(_payload.pop('exp'))
#         if time.time() > exp:
#             print('已失效')
#             return False
#         return payload == _payload


if __name__ == '__main__':
    user_id = 123
    token = generate_jwt_token(user_id)
    print(token)
    print(verify_jwt_token(user_id, token))